﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace WebCrawler
{
    class HTTPSRequest
    {
        public static void ProcessRequest()
        {
            //类似浏览器确认证书合法方法的绑定
            ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://services3.cic.gc.ca/ecas/authenticate.do?app=ecas");

            string param = "test=true";
            byte[] bs = Encoding.UTF8.GetBytes(param);

            //这2句代码表示如果要求客户端证书，将客户端证书加入request，不需要客户端证书的https请求则不需要此代码
            X509Certificate cer = new X509Certificate("C:\\Users\\Camel\\Downloads\\Federal.cer");
            request.ClientCertificates.Add(cer);

            request.UserAgent = "test";
            request.Method = "post";

            using (Stream reqStram = request.GetRequestStream())
            {
                reqStram.Write(bs, 0, bs.Length);
            }

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }

            Console.ReadKey();
        }
        //该方法用于验证服务器证书是否合法，当然可以直接返回true来表示验证永远通过。服务器证书具体内容在参数certificate中。可根据个人需求验证
        //该方法在request.GetResponse()时触发
        public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
            return false;
        }
    }
}
